package com.hmdp.utils;

import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:有关登录拦截器的创建
 * User: dell
 * Date: 2023-05-07
 * Time: 11:11
 */
//创建拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session
        HttpSession session = request.getSession();
        //2.从session中拿到用户信息
        Object user = session.getAttribute("user");
        if(user==null){
            //3.如果不存在直接拦截  返回401状态 未授权
            response.setStatus(401);
            return false;
        }
        //4.存在  保存到ThreadLocal中实现共享
        UserHolder.saveUser((UserDTO) user);
        //5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //避免造成内存泄露
        UserHolder.removeUser();
    }
}
